import pymysql
import joblib
from CoolProp import AbstractState
# from CoolProp.CoolProp import PhaseSI, PropsSI, get_global_param_string
import CoolProp.CoolProp as CoolProp
from CoolProp.HumidAirProp import HAPropsSI

def PropsSI(*args):
    try:
        return CoolProp.PropsSI(args[0], args[1], args[2], args[3], args[4], args[5])
    except:
#         print("something wrong")
        return -1
    
def PhaseSI(*args):
    try:
        return CoolProp.PhaseSI(args[0], args[1], args[2], args[3], args[4])
    except:
#         print("something wrong")
        return -1


class SQL:
    def __init__(self):
        self.db = pymysql.connect(
                    user="xieck",
                    password="123",
                    host="localhost",
                    database="turbine"
                )
        self.cursor = self.db.cursor()
        
    def disconnect(self):
        self.db.close()
    
    def read_data(self, default_dict, idx):
        sql = "SELECT * FROM cndata WHERE id = %s" % (idx)
        try:
            # 执行SQL语句
            self.cursor.execute(sql)
            # 获取所有记录列表
            data = self.cursor.fetchall()[0]

            for i, key in enumerate(default_dict):
                default_dict[key] = data[i+1] # 跳过id
        except:
            print ("Error: unable to fetch data")
            
    def update_data(self, default_dict, idx):    
        sql = "UPDATE cndata SET "
        keys = list(default_dict.keys())
        values = list(default_dict.values())
        tmp_sql = [key + " = " + str(default_dict[key]) for key in default_dict]
        sql += ",".join(tmp_sql)
        sql += " WHERE id = %s" % (idx)
        try:
            # 执行sql语句
            self.cursor.execute(sql)
            # 执行sql语句
            self.db.commit()
        except:
            # 发生错误时回滚
            self.db.rollback()         